package com.example.demo.service.impl;

import com.example.demo.domain.ProductOrder;
import com.example.demo.service.JsonUtils;
import com.example.demo.service.ProductClient;
import com.example.demo.service.ProductOrderService;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.Date;

import java.util.UUID;

@Service
public class ProductOrderServiceImpl implements ProductOrderService {


//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

//    @Autowired
//    private LoadBalancerClient loadBalancer;

    @Override
    public ProductOrder save(int userId, int productId) {
        String response = productClient.findById(productId);
        JsonNode jsonNode = JsonUtils.str2JsonNode(response);
//        Map<String,Object> productMap = restTemplate.getForObject("http://product-service/api/v1/product/find?id="+productId, Map.class);
//        System.out.println(productMap);

//        ServiceInstance instance = loadBalancer.choose("product-service");
//        String url = String.format("http://%s:%s/api/v1/product/find?id="+productId, instance.getHost(),instance.getPort());
//        RestTemplate restTemplate = new RestTemplate();
//        Map<String,Object> productMap = restTemplate.getForObject(url, Map.class);
//        System.out.println(productMap);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());
        productOrder.setProductName(jsonNode.get("name").toString());
        productOrder.setPrice(Integer.parseInt(jsonNode.get("price").toString()));
        return productOrder;
    }
}
